<template>
  <div :id="self.name"
  :class="'c-'+self.name"
  style="position: relative;
          width: 100%;
          height: 90vh;
          margin: 0;
          padding: 0;"
  >
    
  </div>
</template>

<script>
import { ref, unref, watch } from 'vue'
import { init } from '/src/utils/base'
import { getSelection } from '/src/utils/index'
import { init as initBase } from './base'

import { post } from "/src/api/index";

export default {
    emits: ['baseMounted'],
    
    setup() {
        let self = {}

        initBase(self)
        
        init(self)

        const baseMounted = (v) => {
          self.onMounted(v);
        }

        self.amis.onEventSetTablesSubmit = {
          click: {
            actions: [
              {
                actionType: "custom",
                script: (a,b,c,d,e,f) => {
                  let ret = self.amis.onAction(a,b,c,d,e,f,{type:'loading'})
                  let {
                    selectedItems,
                    workspace_name,
                    formComponent,
                  } = ret
                  if (!workspace_name) {
                    ret.loadingComponent.setData(ret.loading_false)
                    self.amis.throw('无法确定生成工作区的名称，请设置工作区条件，或选择一条数据后再操作')
                  }
                  let tables = formComponent.props.body
                    .filter( ele => ele.body[0].name.indexOf('--') < 0 && formComponent.props.data[ele.body[0].name])
                    .map( ele => {
                      let name = ele.body[0].name
                      let alias = formComponent.props.data[ele.body[0].name+'_alias']
                      if (alias && alias != name) {
                        return name + ' as ' + alias
                      } else {
                        return name
                      }
                    })
                    .join(',')
                  let count = selectedItems.length;
                  selectedItems.forEach( ele => {
                    post('sdp_project', 'update', {id:ele.id, tables})
                    .then(data => {
                      if (count == 1) {
                        self.amis.toast.success('成功')

                        throw new Error('finish')
                      }
                      count--;
                    })
                    .catch(data => {
                      count--;
                      if (count == 0) {
                        ret.crudComponent.handleQuery();
                        ret.loadingComponent.setData(ret.loading_false)
                        b({actionType: 'closeDialog',})

                        if (data+'' != 'Error: finish') {
                          self.amis.throw(data)
                        }
                      }
                    })

                  })
                }
              }
            ],
          }
        }
        
        self.amis.onEventSetTables = {
          click: {
            actions: [
              {
                actionType: "custom",
                script: (a,b,c,d,e,f) => {
                  let ret = self.amis.onAction(a,b,c,d,e,f)
                  let {
                    selectedItems,
                    filter,
                    workspace_name,
                  } = ret
                  if (!workspace_name) {
                    self.amis.throw('无法确定生成工作区的名称，请设置工作区条件，或选择一条数据后再操作')
                  }
                  if (ret.loading_name) {
                    if (ret.loadingComponent.getData()[ret.loading_name]) {
                      self.amis.throw('请稍后操作')
                    }
                    ret.loadingComponent.setData(ret.loading_true)
                  }
                  post('sdp_workspace', 'get_table_list', {workspace_name: workspace_name})
                  .then(data => {
                    ret.loadingComponent.setData(ret.loading_false)
                    let tables = []
                    selectedItems.forEach( ele => {
                      if (ele.tables) {
                        ele.tables.split(',').forEach( t => {
                          let name = t.trim()
                          let alias = ''
                          if (name.indexOf(' as ') > 0) {
                            alias = name.split(' as ')[1].trim()
                            name = name.split(' as ')[0].trim()
                          }
                          if (!tables.find(t => t.name == name && t.alias == alias)) {
                            tables.push({name, alias, checked: true})
                          }
                        })
                      }
                    })
                    data.forEach( ele => {
                      if (ele.name.indexOf('--') == 0) {
                        return;
                      }
                      let ot = tables.find( e => e.name == ele.name)
                      if (ot) {
                        ot.remark = ele.remark
                        ele = ot
                      } else {
                        tables.push(ele)
                      }
                      if (ele.remark) {
                        ele.label = ele.name+'('+ele.remark+')'
                      } else {
                        ele.label = ele.name
                      }
                    })
                    let columns = [
                      {
                        type: 'group',
                        className: 'c-set-tables',
                        body: [
                          {
                            name: '--tip_name',
                            label: '【表注释（表名）】 - 【是否生成代码】',
                            labelAlign: 'right',
                            type: "switch",
                            disabled: true,
                            className: 'c-set-tables-1',
                          },
                          {
                            name: '--tip_alias',
                            label: false,
                            type: "static",
                            value: '【别名】',
                            className: 'c-set-tables-2',
                          }
                        ],
                      }
                      
                    ]
                    tables.forEach(ele => {
                      let column = {
                        name: ele.name,
                        label: ele.label,
                        labelAlign: 'right',
                        type: "switch",
                        className: 'c-set-tables-1',
                      }
                      column.value = ele.checked || false
                      let column_alias = {
                        name: ele.name+'_alias',
                        label: false,
                        type: "input-text",
                        clearable: true,
                        value: ele.alias,
                        className: 'c-set-tables-2',
                      }
                      columns.push(
                        {
                          type: 'group',
                          className: 'c-set-tables',
                          body: [
                            column,
                            column_alias,
                          ],
                        }
                      )
                    })

                    b({
                      actionType: 'dialog',
                      dialog: {
                        className: 'c-set-tables-dialog',
                        "size": "full",
                        affixFooter:true,
                        title: "设置表及别名",
                        size: "md",
                        body: {
                          type: "form",
                          onInit:(a,b,c,d,e,f) => {
                            self.amis.enableDialogDrag();
                          },
                          affixFooter:true,
                          body: columns,
                        },
                        "actions": [
                          {
                            type: 'submit',
                            label: '取消',
                          },
                          {
                            "type": "button",
                            "label": "确认",
                            level: 'primary',
                            loadingOn: "${button_batch_edit_loading}",
                            onEvent: self.amis.onEventSetTablesSubmit,
                          },
                        ],
                      },
                    })

                  })
                },
              },
            ],
          },
        }
        self.amis.onEventSetRootPath = {
          click: {
            actions: [
              {
                actionType: "custom",
                script: (a,b,c,d,e,f) => {
                  let ret = self.amis.onAction(a,b,c,d,e,f,{type:'loading'})
                  let {
                    selectedItems,
                    filter,
                  } = ret;
                  let items = selectedItems.filter( ele => ele.root_path && ele.root_path.indexOf('(root)') >= 0)
                  if (!items || !items.length) {
                    self.amis.throw('请先选择未设置(root)路径的条目')
                  }

                  self.amis.prompt('路径', '', '请输入(root)路径', '确定')
                  .then( data => {
                    if (!data || !data.text || !data.text.trim()) {
                      self.amis.throw('请输入路径')
                    }
                    let count = items.length
                    items.forEach(ele => {
                      post('sdp_project', 'update', {id:ele.id, root_path:ele.root_path.replace('(root)', data.text.trim())})
                      .then(data => {
                        if (count == 1) {
                          self.amis.toast.success('成功')

                          throw new Error('finish')
                        }
                        count--;
                      })
                      .catch(data => {
                        count--;
                        if (count == 0) {
                          ret.crudComponent.handleQuery();
                          ret.loadingComponent.setData(ret.loading_false)

                          if (data+'' != 'Error: finish') {
                            self.amis.throw(data)
                          }
                        }
                      })

                    })
                  })
                },
              },
            ],
          },
        }

        let columns = [
          {
            name: 'tables',
            "type": "tpl",
            sortable: true,
            edit: {
              type: 'textarea',
              onEvent: self.amis.onEditChange,
            },
            copyable: true,
            "tpl": "${tables|truncate:16}",
            "popOverEnableOn": "${ tables && tables.length > 16 }",
            "popOver": {
              trigger: 'hover',
              "position": "left-top",
              "showIcon": true,
              "title": {
                type: "operation",
                buttons: [   
                  {
                    type: "button",
                    label: "复制",
                    "actionType": "copy",
                    "content": "${tables}",
                  },
                ],
              },
              "body": {
                "type": "tpl",
                "tpl": "${tables}"
              }
            }
          },
          {
            name: 'remark',
            "type": "tpl",
            edit: {
              type: 'textarea',
              onEvent: self.amis.onEditChange,
            },
            copyable: true,
            "tpl": "${remark|truncate:16}",
            "popOverEnableOn": "${ remark && remark.length > 16 }",
            "popOver": {
              trigger: 'hover',
              "position": "left-top",
              "showIcon": true,
              "title": {
                type: "operation",
                buttons: [   
                  {
                    type: "button",
                    label: "复制",
                    "actionType": "copy",
                    "content": "${remark}",
                  },
                ],
              },
              "body": {
                "type": "tpl",
                "tpl": "${remark}"
              }
            }
          },
        ]

        self.amis.init({columns,
          insert_edit_actions:[
          ],
          insert_edit_bulk_actions: [
          ],
          append_header_actions: [
            {
              type: "button",
              level: "success",
              align: "right",
              label: "生成文件",
              confirmText: "确定要生成文件？",
              loadingOn: "${button_batch_create_file_loading}",
              onEvent: self.amis.onEventCreateFile,
            },
          ]
        })

        let schema = {
          ...self.amis.page_schema,
          body: [    
            {
              type: "crud",
              ...self.amis.commonSchema.crud,
              bulkActions: [
                {...self.amis.commonSchema.bulkActions.delete},
                {...self.amis.commonSchema.bulkActions.edit},
                {...self.amis.commonSchema.bulkActions.batchUpdateValue},
                {
                  type: "button",
                  label: "设置表及别名",
                  loadingOn: "${button_set_tables_loading}",
                  onEvent: self.amis.onEventSetTables,
                },
                {
                  type: "button",
                  label: "设置(root)路径",
                  onEvent: self.amis.onEventSetRootPath,
                },
              ],
              filter: {
                title: '',
                persistData:unref(self.name)+'_filter',
                body: [
                  {...self.amis.commonSchema.filter.page_title},
                  {...self.amis.commonSchema.filter.workspace_name},
                  {
                    type: "input-text",
                    name: "name_like",
                    "clearable": true,
                    "placeholder": "请输入名称",
                    static: false,
                    width: 200,
                    size:'sm',
                  },
                  {
                    type: "input-text",
                    name: "tables_like",
                    "clearable": true,
                    "placeholder": "请输入表",
                    static: false,
                    width: 200,
                    size:'sm',
                  },
                  {...self.amis.commonSchema.filter.search},
                ],
              },
            },
          ],
        }

        self.initAmis('#'+unref(self.name), schema)
        
        return {self:ref(self), baseMounted};
    },
};
</script>

<style>
.c-set-tables>:first-child{
  flex-grow: 2;
}
.c-set-tables>:first-child .cxd-Form-label{
  width:85%;
}

.c-set-tables-dialog .cxd-Modal-body {
  max-height: 70vh;
  overflow: scroll;
  overflow-x: auto;
}

</style>